<template>
	<view class="title">
		<input  v-model="inputValueTitle" @blur="checkPriceInput"  
      :class="{ 'error-input': isError }" type="text" placeholder="请输入商品名称"/>
	 
	</view>
	<!-- 价格 -->
	<view class="price-num">
		<view class="price">
			价格
		</view>
		<view class="num">￥
			<input class="num_price" v-model="inputValue" type="text" placeholder="0.00"/>
			<uni-icons  class="num_icon" type="right" size="15"></uni-icons>
		</view>
	</view>
	<!-- 价格 -->
	<view class="price-num">
		<view class="price">
			原价
		</view>
		<view class="num">￥
			<input class="num_price"  v-model="inputOriginalValue" type="text" placeholder="0.00"/>
			<uni-icons  class="num_icon" type="right" size="15"></uni-icons>
		</view>
	</view>
	<!-- 选择分类 -->
	<view class="classification">
		<view class="class-name">
			选择分类
		</view>
		<view class="class-picker">
			<picker @change="bindPickerChange" :value="index" :range="classificationList" range-key="name">
				 <view  class="uni-input" >
					 {{classificationList[index].name}}
					 <uni-icons type="right" size="15"></uni-icons>
				 </view>
			</picker>
		</view>
	</view>
	<!-- 几成新 -->
	<view class="almost-new">
		<view class="almost">
			几成新
		</view>
		<view class="num">
			<picker @change="almostPickerChange" :range="arrayAlmost" >
				 <view  class="uni-input" >
					 {{arrayAlmost[almostIndex]}}
					 <uni-icons type="right" size="15"></uni-icons>
				 </view>
			</picker>
		</view>
	</view>
	<view class="release-goods">
		<!-- 发布的文字内容 -->
		<textarea class="comment-text" maxlength="-1"  auto-height placeholder="描述宝贝的品牌型号、功能成色、出手原因等" v-model="commentText"></textarea> 
		<!-- 上传视频或者图片 -->
		<view class="up-page">
			<!--图片-->
			<view class="show-box" v-for="(item,index) in imageList" :key="index">
				<image class="full" :src="item" :data-src="image" @tap="previewImage(item)">
				</image>
				<view class="delect-icon" @tap="delect(index)">
					<image class="full" :src="clearIcon" mode=""></image>
				</view>
			</view>
			
			<view v-if="VideoOfImagesShow" @tap="chooseVideoImage" class="box-mode">
				<image class="full" :src="selectfile" mode=""></image>
			</view>
		</view>
	</view>
	
	<view class="down-page">
		<button class="mini-btn"  @click="submitComment">发布</button>
	</view>
	 
	 
</template>
<script>
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	];
	import { mapState} from 'vuex'
	export default {
		data() {
			return {
				// 图标
				clearIcon: '',
				selectfile: '',
				VideoOfImagesShow: true, // 页面图片或视频数量超出后，拍照按钮隐藏
				imageList: [], //存放图片的地址
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				sourceTypeIndex: 2,
				cameraList: [{
					value: 'back',
					name: '后置摄像头',
					checked: 'true'
				}, {
					value: 'front',
					name: '前置摄像头'
				}],
				inputOriginalValue: '',
				inputValue: '',
				inputValueTitle: '',
				cameraIndex: 0, //上传视频时的数量
				maxCount:6,//图片和视频允许上传的总数
				nowCount: 0,//剩余可选择的数量
				commentText: '',
				showEmotions: false,
				//图片的地址
				uploadUrl: '',
				classificationList: [{name:'其他'}],
				arrayAlmost: ['1成','2成','3成','4成','5成','6成','7成','8成','9成','全新'],
				index: 0,
				//是社团发布的话就是社团id
				associationId: 0,
				image: '',
				// 请求参数对象
				queryObj: {
					// 页码值
					pageNo: 1,
					// 每页显示多少条数据
					pageSize: 10
				},
				//5成新
				almostIndex: 5,
				isError: false, // 控制是否显示错误信息  
				
			}
		},
		computed: {
		  ...mapState('m_user', ['userId']),
			//学校id
		  ...mapState('m_dept', ['deptId']),
			formattedMoney() {
		        // 格式化金钱，例如保留两位小数
		        return this.money.toFixed(2);
		    }
		},
		onLoad(options) {
			//不显示上传图片的+
			this.VideoOfImagesShow=true
			this.associationId=options.associationId
			this.getClassificationList()
			
		},
		onUnload() {
			(this.imageList = []), (this.sourceTypeIndex = 2), (this.sourceType = ['拍摄', '相册', '拍摄或相册']);
		},
		methods: {
			toggleEmotions() {
				this.showEmotions = !this.showEmotions;
			},
			
			addEmotion(emotionCode) {
				if (emotionCode == "") return;
				this.commentText += emotionCode
			},
			//点击上传图片或视频
			chooseVideoImage() {
				uni.showActionSheet({
					title: '选择上传类型',
					itemList: ['图片'],
					success: res => {
						console.log(res);
						this.chooseImages();
					}
				});
			},
			//上传图片
			 chooseImages() {
				this.nowCount=this.maxCount-this.imageList.length
				uni.chooseImage({
					count: this.nowCount, //允许选择的数量
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: res => {
						const tempFilePaths = res.tempFilePaths;
						 
						this.imageList = this.imageList.concat(tempFilePaths);
						
						for (let i = 0; i < tempFilePaths.length; i++) {
							const result =  this.uploadFilePromise(tempFilePaths[i],0)
							
						}
						
						//console.log(this.imageList)
						if (this.imageList.length >= this.maxCount) {
							this.VideoOfImagesShow = false; //图片上传数量和count一样时，让点击拍照按钮消失
						}else{
							this.VideoOfImagesShow = true;
						}
					}
				})
			},
			
			//预览图片
			previewImage: function(e) {
				console.log(e)
				uni.previewImage({
					current: e,
					urls: this.imageList
				});
			},
			// 删除图片
			delect(index) {
				uni.showModal({
					title: '提示',
					content: '是否要删除该图片',
					success: res => {
						if (res.confirm) {
							this.imageList.splice(index, 1);
						}
						if (this.imageList.length  == this.maxCount) {
							this.VideoOfImagesShow = false;
						} else {
							this.VideoOfImagesShow = true;
						}
					}
				});
			},
		
			
			 uploadFilePromise(url,flag) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						
						url: uni.$http.baseUrl+'/common/sysFile/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
						},
						
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.imgUrl)
								const imgUrl=JSON.parse(res.data).imgUrl
								if(flag==0){
									if(this.uploadUrl.length==0){
										this.uploadUrl+=imgUrl
									}else{
										this.uploadUrl+=","+imgUrl
									}
									console.log(this.uploadUrl)
								}else{
									if(this.uploadVideoUrl.length==0){
										this.uploadVideoUrl+=imgUrl
									}else{
										this.uploadVideoUrl+=","+imgUrl
									}
								}
								
							}, 1000)
							
						}
					});
				})
			},
			prompt(title){
				uni.showToast({
					icon: "error",
					title: title,
				})
			},
			//必须是数字
			 isNumericWithDecimalStrict(value) {  
			  // 更严格的正则表达式，不允许以小数点开头或末尾只有一个小数点  
			  const regex = /^[-+]?\d+(\.\d+)?$/;  
			  return regex.test(value);  
			} ,
			submitComment() {
				console.log(this.isNumericWithDecimalStrict(this.inputValue.trim()));
				//校验，标题、内容、价格、分类不饿能为空，为空时提示
				if(!this.inputValueTitle.trim()){
					this.prompt("名称不能为空")
				}else if(!this.commentText.trim()){
					this.prompt("描述不能为空")
				}else if(!this.uploadUrl.trim()){
					this.prompt("必须上传图片")
				}else if(!this.inputValue.trim()){
					this.prompt("价格不能为空")
				}else if(!this.isNumericWithDecimalStrict(this.inputValue.trim())){
					this.prompt("价格必须是数字")
				}else if(!this.isNumericWithDecimalStrict(this.inputOriginalValue.trim())&&!this.inputValue.trim()){
					this.prompt("原价必须是数字")
				}else{
					console.log("============")
					// ... 发送评论逻辑
					this.submitCommentTo();
				}
				
				
			},
			//发布商品
			async submitCommentTo() {
				await uni.request({
					url: uni.$http.baseUrl + '/api/mobileMall/addProduct',
					data: {
						//商品分类
						categoryId:  this.classificationList[this.index].id,
						categoryName:  this.classificationList[this.index].name,
						//卖方id
						sellerId: this.userId,
						//标题
						productName: this.inputValueTitle,
						//商品价格
						productPrice: this.inputValue,
						productPictures: this.uploadUrl,
						productDesc:this.commentText,
						exp1: this.uploadUrl.split(",")[0],
						
					},
					method: 'POST',
					header: {
						 "Content-Type": "application/json",
						//"Content-Type": "application/x-www-form-urlencoded"
					},
					success: (res) => {
						this.info = res.data.data
						uni.navigateBack();
						uni.showToast({
							icon: "none",
							title: "发布完成"
						})
						// 发送刷新事件
						  uni.$emit('refreshPage');
					},
					fail: (res) => {
						if (res.statusCode !== 200) return uni.$showMsg()
					}
				});
			},
			checkPriceInput() {  
				// if(this.inputValueTitle==''){
				// 	this.isError=false
				// }
				      this.isError = !this.inputValueTitle.trim(); // 如果价格为空（去除首尾空格后），则设置isError为true  

			}, 
			bindPickerChange: function(e) {
				this.index = e.detail.value
			},
			almostPickerChange: function(e) {
				this.almostIndex = e.detail.value
			},
			//获取商品分类
			async getClassificationList() {
				 await uni.request({
					 url: uni.$http.baseUrl+'/api/mobileMall/getCategoryList',
					 data: {
						
						
					 },
					method: 'POST',
					 header: {
						   // "Content-Type": "application/json",
						   "Content-Type": "application/x-www-form-urlencoded"
						 },
					 success: (res) => {
						this.classificationList=res.data.data
					 },
					fail: (res) =>{
						if (res.statusCode !== 200) return uni.$showMsg()
					}
				 });
			 },
			
		}
	}
</script>
<style lang="scss">
	
	/* 统一上传后显示的盒子宽高比 */
	.box-mode {
		width: 27vw;
		height: 27vw;
		
		border-radius: 8rpx;
		overflow: hidden;
	}
	
	.full {
		width: 100%;
		height: 100%;
	}
 
	.up-page {
		display: flex;
		flex-wrap: wrap;
		display: flex;
		width: 100%;
		.show-box:nth-child(3n){
			margin-right: 0;
		}
		.show-box {
			position: relative;
			margin-bottom:4vw;
			margin-right: 4vw;
			@extend .box-mode;
 
			.delect-icon {
				height: 40rpx;
				width: 40rpx;
				position: absolute;
				right: 0rpx;
				top: 0rpx;
				z-index: 1000;
			}
		}
	}
.release-goods{
	border-radius: 8px;
	background-color: white;
	margin: 3px;
	margin-top: 0px;
	//height: 300px;
}
.comment-text{
	padding-top: 5px;
	width: 98%;
	margin: 10px;
}
.down-page{
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	.mini-btn{
		height: 40px;
		border-radius: 20px;
		color: white;
		background-color: #017c95;
	}
}
.title{
	background-color: white;
	border-radius: 8px;
	background-color: white;
	font-size: 16px;
	margin: 3px;
	height: 40px;
	padding: 5px;
}
.error-input {  
  border-color: red; /* 或者使用border属性来完全自定义边框样式 */  
}
.error-message {  
  color: red;  
  margin-top: 5px; /* 根据需要调整间距 */  
}
.price-num,.classification,.almost-new{
	border-radius: 8px;
	background-color: white;
	font-size: 16px;
	display: flex;
	justify-content: space-between;
	padding: 10px;
	margin-bottom: 5px;
	.num{
		display: flex;
		input{
			width: 40px;
		}
	}
}

 
</style>
